from flask import Blueprint, render_template, request, send_from_directory, jsonify, current_app
from flask_login import login_required, current_user
import os
from datetime import datetime
from werkzeug.utils import secure_filename
from .models import File
from .database import db
from .utils import allowed_file, format_size

file_bp = Blueprint('file', __name__)

@file_bp.route('/')
@login_required
def index():
    files = File.query.filter_by(user_id=current_user.id).order_by(File.upload_time.desc()).all()
    
    formatted_files = []
    for file in files:
        formatted_files.append({
            'id': file.id,
            'name': file.filename,
            'description': file.description or '暂无描述',
            'size': format_size(file.size),
            'date': file.upload_time.strftime('%Y-%m-%d %H:%M')
        })
    
    return render_template('file/index.html', files=formatted_files)

@file_bp.route('/upload', methods=['POST'])
@login_required
def upload():
    if 'file' not in request.files:
        return jsonify(error="没有选择文件",code=400), 200

    
    file = request.files['file']
    description = request.form.get('description', '')
    
    if file.filename == '':
        return jsonify(error="没有选择文件",code=400), 200
    
    
    if not allowed_file(file.filename, current_app.config['ALLOWED_EXTENSIONS']):
        allowed = ', '.join(current_app.config['ALLOWED_EXTENSIONS'])
        return jsonify(error=f'不支持的文件类型，请上传以下类型: {allowed}'), 200
    
    filename = secure_filename(file.filename)
    file_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
    
    # 避免文件覆盖
    counter = 1
    base_name, ext = os.path.splitext(filename)
    while os.path.exists(file_path):
        filename = f"{base_name}_{counter}{ext}"
        file_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
        counter += 1
    
    try:
        file.save(file_path)
        file_size = os.path.getsize(file_path)
        
        new_file = File(
            filename=filename,
            description=description,
            size=file_size,
            path=file_path,
            user_id=current_user.id
        )
        
        db.session.add(new_file)
        db.session.commit()
        
        return jsonify(error='文件上传成功!',code=200), 200
    except Exception as e:
        if os.path.exists(file_path):
            os.remove(file_path)
        return jsonify(error=f'文件上传失败: {str(e)}',code=500), 200
    


@file_bp.route('/delete/<int:file_id>', methods=['POST'])
@login_required
def delete(file_id):
    file = File.query.get_or_404(file_id)
    
    if file.user_id != current_user.id:
        return jsonify({'success': False, 'message': '无权删除此文件'}), 403
    
    try:
        file_path = file.path
        db.session.delete(file)
        db.session.commit()
        
        if os.path.exists(file_path):
            os.remove(file_path)
        
        return jsonify({'success': True, 'message': '文件删除成功'})
    except Exception as e:
        return jsonify({'success': False, 'message': f'删除失败: {str(e)}'}), 500

@file_bp.route('/download/<filename>')
@login_required
def download(filename):
    file = File.query.filter_by(filename=secure_filename(filename), user_id=current_user.id).first_or_404()
    print(current_app.config['UPLOAD_FOLDER'])
    return send_from_directory(current_app.config['UPLOAD_FOLDER'], secure_filename(filename), as_attachment=True)